<div class="row">
    <div class="col-sm-12 col-md-6">
        <div class="panel panel-default" id="network-stats">
        <div class="panel-heading">
            <h3 class="panel-title"><i class="fa fa-tasks fa-fw" aria-hidden="true"></i> Stats</h3>
          </div>
          <div class="panel-body">
            <div class="row">
                <div class="col-sm-6 col-md-6">
                    <ul class="nav nav-pills nav-stacked">

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Blockchain height, total amount of blocks starting from zero."><i class="fa fa-bars"></i> Height: <span id="networkHeight"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="The number of transactions in the network (excluding coinbase, i.e. reward for mined blocks)."><i class="fa fa fa-exchange"></i> Transactions: <span id="networkTransactions"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Current Base Reward (for last mined block)."><i class="fa fa-certificate"></i> Reward: <span id="currentReward"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Total Royalties supply in circulation."><i class="fa fa-money"></i> Supply: <span id="totalCoins"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="bottom" data-original-title="Total % of all Royalties locked in deposits."><i class="fa fa-percent" aria-hidden="true"></i> Deposited: <span id="depositPercent"></span> %</a></li>

                    </ul>
                </div>
                <div class="col-sm-6 col-md-6">
                    <ul class="nav nav-pills nav-stacked">

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Difficulty for next block. Ratio at which at the current hashing speed blocks will be mined with 4 minutes interval."><i class="fa fa-unlock-alt"></i> Difficulty: <span id="networkDifficulty"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Average difficulty by last 30 blocks."><i class="fa fa-lock"></i> Average Difficulty: <span id="avgDifficulty"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Current estimated network hash rate. Calculated by current difficulty."><i class="fa fa-tachometer"></i> Hash Rate: <span id="networkHashrate"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="top" data-original-title="Average estimated network hash rate. Calculated by average difficulty."><i class="fa fa-clock-o"></i> Average Hash Rate: <span id="avgHashrate"></span></a></li>

                        <li><a href="#" data-toggle="tooltip" data-placement="bottom" data-original-title="Estimated block solve time at estimated network speed and current difficulty."><i class="fa fa-circle-o-notch" aria-hidden="true"></i> Solve time: <span id="blockSolveTime"></span></a></li>

                    </ul>
                </div>
            </div>

          </div>
        </div>
    </div>

    <div class="col-sm-6 col-md-6">
        <div class="panel panel-default">
          <div class="panel-heading">

            <h3 class="panel-title"><i class="fa fa-area-chart" aria-hidden="true"></i> Charts
                <span class="text-default" data-toggle="tooltip" data-placement="right" data-original-title="Difficulty based on last blocks from the list below. Block size, transactions count. Load more blocks to enlarge chart range."><i class="fa fa-question-circle"></i></span>
            </h3>

          </div>
          <div class="panel-body chart-wrapper">
            <canvas id="difficultyChart" height="210"></canvas>
          </div>
        </div>
    </div>
</div>


<div class="panel panel-default">
    <div class="panel-heading">

        <h3 class="panel-title"><i class="fa fa-exchange fa-fw" aria-hidden="true"></i> Transaction pool
            <span id="mempool_count" class="badge"></span>
            <span class="text-default" data-toggle="tooltip" data-placement="right" data-original-title="Recent transactions waiting to be included into a block. Once it happens a transaction gets into the blockchain and becomes confirmed."><i class="fa fa-question-circle"></i></span>
        </h3>

    </div>
    <div class="panel-body">

        <div>
            <div class="table-responsive">
                <table class="table table-hover" id="mem_pool_table">
                    <thead>
                        <tr>
                            <!-- <th width="30%"><i class="fa fa-clock-o"></i> Date &amp; time</th> -->
                            <th width="10%"><i class="fa fa-money"></i> Amount</th>
                            <th width="10%"><i class="fa fa-tag"></i> Fee</th>
                            <th width="10%"><i class="fa fa-archive"></i> Size</th>
                            <th width="70%"><i class="fa fa-paw"></i> Hash</th>
                        </tr>
                    </thead>
                    <tbody id="mem_pool_rows">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title"><i class="fa fa-chain fa-fw" aria-hidden="true"></i> Recent blocks</h3>
    </div>
    <div class="panel-body">
        <div class="row">
            <div class="col-sm-8 col-md-6 col-lg-5">
                <div class="input-group">
                    <a id="prev-page" href="#" class="btn btn-default input-group-addon"><i class="fa fa-arrow-left" aria-hidden="true"></i> Older</a>
                    <span class="input-group-addon">№</span>
                    <input id="goto-height" type="text" class="form-control" placeholder="Height">
                    <a id="goto-height-go" href="#" class="btn btn-default input-group-addon">Go</a>
                    <a id="next-page" href="#" class="btn btn-default input-group-addon disabled">Newer <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th><i class="fa fa-bars"></i> Height</th>
                        <th><i class="fa fa-clock-o"></i> Date &amp; time</th>
                        <th><i class="fa fa-archive"></i> Size</th>
                        <th><i class="fa fa-paw"></i> Block Hash</th>
                        <th><i class="fa fa-unlock-alt"></i> Difficulty</th>
                        <th><i class="fa fa-bars"></i> Transactions</th>
                    </tr>
                </thead>
                <tbody id="blocks_rows">

                </tbody>
            </table>
        </div>

        <p class="text-center">
            <button type="button" class="btn btn-default" id="loadMoreBlocks">Load More</button>
        </p>

    </div>
</div>

<script>
    var block,
    Difficulties = [],
    Blocks = [],
    Rewards = [],
    Txses = [],
    Sizes = [],
    Timestamps = [],
    diffChart;

    currentPage = {
        destroy: function(){
            if (xhrGetBlocks) xhrGetBlocks.abort();
        },
        init: function(){
            $.when(
                renderInitialBlocks()
            ).then(function() {
                setTimeout(function(){
                    displayDiffChart();
                    refreshChart();
                }, 500)
            });
        },
        update: function(){
            renderLastBlock();
            updateText('networkHeight', lastStats.height.toString());
            updateText('networkTransactions', lastStats.tx_count.toString());
            updateText('networkHashrate', getReadableHashRateString(lastStats.difficulty / blockTargetInterval));
            updateText('networkDifficulty', getReadableDifficultyString(lastStats.difficulty, 0).toString());
            $("time.timeago").timeago();
            getPoolTransactions();
            var currHeight = $('#blocks_rows').children().first().data('height');
            if((currHeight + 31) > lastStats.last_known_block_index){
                $.when(
                    renderInitialBlocks()
                ).then(function() {
                    setTimeout(function(){
                        refreshChart();
                    }, 100)
                });
            }
            if((currHeight + 31) < lastStats.last_known_block_index){
                $('#next-page').removeClass('disabled');
            }
        }
    };

    function renderLastBlock(){
        $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"getlastblockheader",
                params: {

                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                last_block_hash = data.result.block_header.hash;
                $.ajax({
                    url: api + '/json_rpc',
                    method: "POST",
                    data: JSON.stringify({
                        jsonrpc:"2.0",
                        id: "test",
                        method:"f_block_json",
                        params: {
                            hash: last_block_hash
                        }
                    }),
                    dataType: 'json',
                    cache: 'false',
                    success: function(data){
                        block = data.result.block;
                        updateText('totalCoins', getReadableCoins(block.alreadyGeneratedCoins,2));
                        updateText('depositPercent', (lastStats.full_deposit_amount / block.alreadyGeneratedCoins * 100).toFixed(4));
                        updateText('currentReward', getReadableCoins(block.baseReward,4));
                    }
                });
            }
        });
    }

    var xhrGetBlocks;
    $('#loadMoreBlocks').click(function(){
        if (xhrGetBlocks) xhrGetBlocks.abort();
        xhrGetBlocks = $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"f_blocks_list_json",
                params: {
                    height: $('#blocks_rows').children().last().data('height')
                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                $.when(
                     renderBlocks(data.result.blocks)
                ).then(function() {
                    setTimeout(function(){
                        loadMoreChart();
                    }, 100)
                });
            }
        });
    });

    $('#prev-page').click(function(e){
        if (xhrGetBlocks) xhrGetBlocks.abort();
        var currHeight = $('#blocks_rows').children().first().data('height');
        var openHeight = (currHeight - 31 < 0) ? 0 : currHeight - 31;

        xhrGetBlocks = $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"f_blocks_list_json",
                params: {
                    height: openHeight
                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                $('#blocks_rows').children().remove();
                $.when(
                    renderBlocks(data.result.blocks)
                ).then(function() {
                    setTimeout(function(){
                        refreshChart();
                    }, 100)
                });
            }
        });
        e.preventDefault();

        if((currHeight + 31) > lastStats.last_known_block_index){
            $('#next-page').removeClass('disabled');
        }
        if((currHeight - 61) < 0){
            $('#prev-page').addClass('disabled');
        }
    });

    $('#next-page').click(function(e){
        if (xhrGetBlocks) xhrGetBlocks.abort();
        var currHeight = $('#blocks_rows').children().first().data('height');
        var openHeight = (currHeight + 31 > lastStats.last_known_block_index) ? (lastStats.last_known_block_index) : currHeight + 31;

        xhrGetBlocks = $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"f_blocks_list_json",
                params: {
                    height: openHeight
                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                $('#blocks_rows').children().remove();
                $.when(
                    renderBlocks(data.result.blocks)
                ).then(function() {
                    setTimeout(function(){
                        refreshChart();
                    }, 100)
                });
            }
        });
        e.preventDefault();

        if((currHeight + 61) > lastStats.last_known_block_index){
            $('#next-page').addClass('disabled');
        }

        $('#prev-page').removeClass('disabled');

    });

    $('#goto-height-go').click(function() {
        var height = document.getElementById('goto-height').value;
        var newUrl = "/?height="+height;
        window.location = newUrl;
    });

    $('#goto-height').keyup(function(e){
        if(e.keyCode === 13)
            $('#goto-height-go').click();
    });

    function renderInitialBlocks(){
        if (xhrGetBlocks) xhrGetBlocks.abort();
        var loadHeight;

        if (urlParam('height'))
            loadHeight = parseInt(urlParam('height'));
        else
            loadHeight = lastStats.last_known_block_index;

        if((loadHeight - 31) < 0){
            $('#prev-page').addClass('disabled');
            $('#next-page').removeClass('disabled');
        }

        xhrGetBlocks = $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"f_blocks_list_json",
                params: {
                    height: loadHeight
                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                renderBlocks(data.result.blocks);
            }
        });
    };

    function getBlockRowElement(block, jsonString){
        var row = document.createElement('tr');
        row.setAttribute('data-json', jsonString);
        row.setAttribute('data-height', block.height);
        row.setAttribute('id', 'blockRow' + block.height);
        row.setAttribute('title', block.hash);
        var dateTime = new Date(block.timestamp * 1000).toISOString();
        row.setAttribute('data-dt', dateTime);
        var columns =
            '<td>' + block.height + '</td>' +
            '<td class="date-time">' + formatDate(block.timestamp) + ' (<time class="timeago" datetime="'+dateTime+'"></time>)</td>' +
            '<td>' + block.cumul_size + '</td>' +
            '<td>' + formatBlockLink(block.hash) + '</td>' +
            '<td class="blk-diff">' + block.difficulty + '</td>' +
            '<td>' + block.tx_count + '</td>';

        Difficulties.push(parseInt(block.difficulty));
        Blocks.push(parseInt(block.height));
        Txses.push(parseInt(block.tx_count));
        Sizes.push(parseInt(block.cumul_size));
        Timestamps.push(dateTime);

        row.innerHTML = columns;

        return row;
    }

    function renderBlocks(blocksResults){
        var $blocksRows = $('#blocks_rows');

        for (var i = 0; i < blocksResults.length; i ++){
            var block = blocksResults[i];
            var blockJson = JSON.stringify(block);
            var existingRow = document.getElementById('blockRow' + block.height);

            if (existingRow && existingRow.getAttribute('data-json') !== blockJson){
                $(existingRow).replaceWith(getBlockRowElement(block, blockJson));
            }
            else if (!existingRow){
                var blockElement = getBlockRowElement(block, blockJson);
                var inserted = false;
                var rows = $blocksRows.children().get();
                for (var f = 0; f < rows.length; f++) {
                    var bHeight = parseInt(rows[f].getAttribute('data-height'));
                    if (bHeight < block.height){
                        inserted = true;
                        $(rows[f]).before(blockElement);
                        break;
                    }
                }
                if (!inserted) {
                    $blocksRows.append(blockElement);
                }
            }
        }
        $("time.timeago").timeago();
        calcAvgHashRate();
    }

    function calcAvgHashRate(){
        var sum = Difficulties.reduce(add, 0);
        function add(a, b) {
            return a + b;
        }
        var avgDiff = Math.round(sum / Difficulties.length);
        var avgHashRate = avgDiff / blockTargetInterval;

        updateText('avgDifficulty', getReadableDifficultyString(avgDiff, 0).toString());
        updateText('avgHashrate', getReadableHashRateString(avgDiff / blockTargetInterval));
        updateText('blockSolveTime', getReadableTime(lastStats.difficulty / avgHashRate));

    }

    //  Karbovanets MemPool Transactions
    function getPoolTransactions(){
        var xhrGetPool = $.ajax({
            url: api + '/json_rpc',
            method: "POST",
            data: JSON.stringify({
                jsonrpc:"2.0",
                id: "test",
                method:"f_on_transactions_pool_json",
                params: {

                }
            }),
            dataType: 'json',
            cache: 'false',
            success: function(data){
                var txsRows = document.getElementById('mem_pool_rows');
                while (txsRows.firstChild) {
                    txsRows.removeChild(txsRows.firstChild);
                }

                var rawTxs = data.result.transactions;
                if (rawTxs.length != 0) {
                    rawTxs.forEach(function(tx, i) {
                        var hash = tx.hash;
                        if(hash != "") {
                            //var timestamp = tx.recieved;
                            var amount = tx.amount_out;
                            var fee = tx.fee;
                            var size = tx.size;
                            var row = document.createElement('tr');
                            var columns =
                                //'<td>' + formatDate(timestamp) + ' (<span class="mtx-ago"></span>)' + '</td>' +
                                '<td>' + getReadableCoins(amount, 4, true) + '</td>' +
                                '<td>' + getReadableCoins(fee, 4, true) + '</td>' +
                                '<td>' + size + '</td>' +
                                '<td>' + /*formatPaymentLink(*/hash/*)*/ + '</td>';
                            row.innerHTML = columns;
                            $(txsRows).append(row);
                            //$(row).find('.mtx-ago').timeago('update', new Date(timestamp * 1000).toISOString());
                        }
                    });
                    updateText('mempool_count', document.querySelectorAll('#mem_pool_rows tr').length);
                }
            }
        });
    };

    // Difficulty chart
    function displayDiffChart() {
        var ctx = document.getElementById("difficultyChart");
        var chartData = {
            //labels: [].concat(Blocks).reverse(),
            labels: [].concat(formatDate(Timestamps)).reverse(),
            datasets: [
              {
                data: [].concat(Blocks).reverse(),
                yAxisID: "Height",
                label: "Height",
                backgroundColor: "rgba(0,0,0,0)",
                borderColor: 'rgba(0,0,0,0)',
                borderWidth: 0,
                pointBorderWidth: 0,
                pointRadius: 0,
                pointHoverRadius: 0,
                pointHitRadius: 0,
                display: false
              },{
                data: [].concat(Difficulties).reverse(),
                yAxisID: "Difficulty",
                label: "Difficulty",
                backgroundColor: "rgba(220,220,220,0.2)",
                borderColor: '#2FA4E7',
                borderWidth: 2,
                pointColor : "#2FA4E7",
                pointBorderColor : "#2FA4E7",
                pointHighlightFill: "#2FA4E7",
                pointBackgroundColor: "#2FA4E7",
                pointBorderWidth: 2,
                pointRadius: 1,
                pointHoverRadius: 3,
                pointHitRadius: 20
              },{
                data: [].concat(Txses).reverse(),
                yAxisID: "Transactions",
                label: "Transactions",
                backgroundColor: "rgba(255,242,0,0.1)",
                borderColor: '#B5E61D',
                borderWidth: 1,
                pointColor : "#B5E61D",
                pointBorderColor : "#B5E61D",
                pointHighlightFill: "#B5E61D",
                pointBackgroundColor: "#B5E61D",
                pointBorderWidth: 1,
                pointRadius: 1,
                pointHoverRadius: 3,
                pointHitRadius: 20
              },{
                data: [].concat(Sizes).reverse(),
                yAxisID: "Sizes",
                label: "Size",
                backgroundColor: "rgba(65,172,0,0.1)",
                borderColor: '#99D9EA',
                borderWidth: 1,
                pointColor : "#99D9EA",
                pointBorderColor : "#99D9EA",
                pointHighlightFill: "#99D9EA",
                pointBackgroundColor: "#99D9EA",
                pointBorderWidth: 1,
                pointRadius: 1,
                pointHoverRadius: 3,
                pointHitRadius: 20
              }
            ]
        };
        var options = {
            responsive: true,
            maintainAspectRatio: false,
            elements: {
                line: {
                    tension: 0
                }
            },
            title: {
                display: false
            },
            legend: {
                display: false
            },
            scales: {
              yAxes: [{
                id: 'Height',
                type: 'linear',
                position: 'left',
                scaleLabel: {
                    display: false,
                    labelString: 'Height'
                },
                gridLines: {
                    display:false
                },
                ticks: {
                    fontSize: 9,
                    display:false
                },
                display: false
              },{
                id: 'Difficulty',
                type: 'linear',
                position: 'left',
                scaleLabel: {
                    display: false,
                    labelString: 'Difficulty'
                },
                gridLines: {
                    display:false
                },
                ticks: {
                    fontSize: 9,
                    display:false
                },
                display: false
              },{
                id: 'Transactions',
                type: 'linear',
                position: 'right',
                scaleLabel: {
                    display: false,
                    labelString: 'Transactions'
                },
                gridLines: {
                    display:false
                },
                ticks: {
                    fontSize: 9,
                    display:false
                },
                display: false
              },{
                id: 'Sizes',
                type: 'linear',
                position: 'right',
                scaleLabel: {
                    display: false,
                    labelString: 'Size'
                },
                gridLines: {
                    display:false
                },
                ticks: {
                    fontSize: 9,
                    display:false
                },
                display: false
              }

              ],
              xAxes: [{
                type: "time",
                time: {
                    parser: false,
                    unit: 'minute',
                    unitStepSize: 60,
                    round: 'second',
                    displayFormats: {
                        'millisecond': 'SSS [ms]',
                        'second': 'HH:mm:ss', // 11:20:01 AM
                        'minute': 'HH:mm', // 11:20:01 AM
                        'hour': 'HH:mm', // Sept 4, 5PM
                        'day': 'MMM Do', // Sep 4 2015
                        'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
                        'month': 'MMM YYYY', // Sept 2015
                        'quarter': '[Q]Q - YYYY', // Q3
                        'year': 'YYYY', // 2017
                    },
                },
                gridLines: {
                    display:false
                },
                ticks: {
                    fontSize: 9,
                    fontColor: "#CCC",
                    autoSkip: true,
                    //maxRotation: 90,
                    //minRotation: 90
                    //display:false
                }
                //display: false
              }]
            },
            tooltips: {
                mode: 'index',
                //displayColors: false,
                callbacks: {
                    title: function(tooltipItem, data) {
                        var height    = data.datasets[3].data[tooltipItem[0].index];
                        var time = new Date(data.labels[tooltipItem[0].index]).toLocaleString();
                        //return 'Блок №: ' + height + ' - ' + time + '';
                        return time + '';
                    },/*
                    label: function(tooltipItem, data) {
                        var diff        = data.datasets[0].data[tooltipItem.index];
                        var txcount    = data.datasets[1].data[tooltipItem.index];
                        var size        = data.datasets[2].data[tooltipItem.index];

                        var diff_swatch_color = data.datasets[0].borderColor;

                        console.log(diff_swatch_color);

                        var diff_swatch = '<span style="color="'+ diff_swatch_color +'">&bullet;</span>';

                        var multistringText = [];

                        var str1 = diff_swatch + 'Складність: ' + diff + '';
                        var str2 = 'Розмір: ' + size + '';
                        var str3 = 'Транзакції: ' + txcount + '';

                        multistringText.push(str1);
                        multistringText.push(str2);
                        multistringText.push(str3);

                        return multistringText;
                    }*/
                }
            }
        };

        diffChart = new Chart(ctx,{
        type: 'line',
        data: chartData,
        options: options
        });
    }

    function refreshChart() {
        var brows   = $('#blocks_rows').children(),
            labels  = [],
            diffs   = [],
            sizes   = [],
            times   = [],
            heights = [],
            txsnr   = [];
        for (var i = 0; i < brows.length; i++) {
            var row = $(brows[i]);
            var label  = parseInt(row.find('td:first').text());
            var diff   = parseInt(row.find('td.blk-diff').text());
            var txses  = parseInt(row.find('td:last').text());
            var size   = parseInt(row.find('td:nth-child(3)').text());
            var time   = row.attr('data-dt');

                labels.push(label);
                diffs.push(diff);
                txsnr.push(txses);
                sizes.push(size);
                times.push(time);
        }
        //diffChart.data.labels = labels.reverse();
        diffChart.data.labels = times.reverse();
        diffChart.data.datasets[0].data = labels.reverse();
        diffChart.data.datasets[1].data = diffs.reverse();
        diffChart.data.datasets[2].data = txsnr.reverse();
        diffChart.data.datasets[3].data = sizes.reverse();

        diffChart.update();
    }

    function loadMoreChart() {
        //diffChart.data.labels = [].concat(Blocks).reverse();
        diffChart.data.labels = [].concat(Timestamps).reverse();
        diffChart.data.datasets[0].data = [].concat(Blocks).reverse();
        diffChart.data.datasets[1].data = [].concat(Difficulties).reverse();
        diffChart.data.datasets[2].data = [].concat(Txses).reverse();
        diffChart.data.datasets[3].data = [].concat(Sizes).reverse();
        diffChart.update();
}

    $(function() {
        $('[data-toggle="tooltip"]').tooltip();
    });

    function getReadableTime(seconds){
        var units = [ [60, 's.'], [60, 'min.'], [24, 'h.'],
            [7, 'd.'], [4, 'w.'], [12, 'м.'], [1, 'y.'] ];

        function formatAmounts(amount, unit){
            var rounded = Math.round(amount);
            return '' + rounded + ' ' + unit + (rounded > 1 ? '' : '');
        }

        var amount = seconds;
        for (var i = 0; i < units.length; i++){
            if (amount < units[i][0])
                return formatAmounts(amount, units[i][1]);
            amount = amount / units[i][0];
        }
        return formatAmounts(amount,  units[units.length - 1][1]);
    }
</script>
<script src="../js/Chart.bundle.min.js"></script>
